from urllib.parse import urlencode  # 新增urllib解析器导入

import requests


class BaiduMapAPI:
    def __init__(self, api_key):
        self.api_key = api_key
        self.ak = api_key  # 保持与现有代码兼容

    def search_places(self, query, region):
        url = f"http://api.map.baidu.com/place/v2/search?query={query}&region={region}&output=json&ak={self.api_key}"
        response = requests.get(url)
        return response.json()

    def get_driving_direction_url(self, origin, destination, waypoints=None, tactics=1):
        url = f"http://api.map.baidu.com/direction/v2/driving?origin={origin}&destination={destination}&tactics={tactics}&ak={self.api_key}"
        if waypoints:
            url += f"&waypoints={waypoints}"
        return url

    def get_riding_direction_url(self, origin, destination, riding_type=0, road_prefer=0):
        url = f"https://api.map.baidu.com/directionlite/v1/riding?origin={origin}&destination={destination}&riding_type={riding_type}&road_prefer={road_prefer}&ak=47jXQbiwPNWVY5GgVPUJYpOiHG5YhBcr"
        return url

    def get_place_details(self, uid):
        """
        获取指定POI的详细信息
        :param uid: POI的唯一标识
        :return: POI的详细信息字典
        """
        params = {
            "uid": uid,
            "scope": 2,
            "output": "json",
            "ak": "47jXQbiwPNWVY5GgVPUJYpOiHG5YhBcr",
        }
        try:
            response = requests.get(
                "https://api.map.baidu.com/place/v2/detail", params=params
            )
            response.raise_for_status()  # 检查HTTP请求是否成功
            data = response.json()
            self.logger.info(f"百度地图API返回的地点详情数据: {data}")

            # 检查API返回的状态码
            if data.get("status") != 0:
                self.logger.error(f"百度地图API返回错误: {data.get('message')}")
                return {}

            # 返回POI的详细信息
            return data.get("result", {})
        except requests.exceptions.RequestException as e:
            self.logger.error(f"百度地图API请求失败: {str(e)}")
            return {}
        except ValueError as e:
            self.logger.error(f"解析百度地图API返回的数据失败: {str(e)}")
            return {}

    def get_direction_url(self, origin, destination, route_type="riding"):
        """
        获取百度地图路线规划URL
        :param origin: 起点坐标
        :param destination: 终点坐标
        :param route_type: 路线规划方式（riding: 骑行, driving: 驾车, walking: 步行, transit: 公交）
        :return: 百度地图路线规划URL
        """
        base_url = "http://api.map.baidu.com/direction/v2/"
        params = {
            "origin": origin,
            "destination": destination,
            "ak": self.api_key,  # 统一使用配置参数
        }
        return f"{base_url}{route_type}?{urlencode(params)}"

    def get_driving_direction_url(self, origin, destination, waypoints=None, tactics=0, origin_road_type=0, gps_direction=None, radius=None, speed=None):
        base_url = "https://api.map.baidu.com/directionlite/v1/driving"
        params = {
            "origin": origin,
            "destination": destination,
            "ak": self.api_key,  # 统一使用配置参数
            "tactics": tactics,
            "origin_road_type": origin_road_type,
        }
        if waypoints:
            params["waypoints"] = "|".join(waypoints)
        if gps_direction is not None:
            params["gps_direction"] = gps_direction
        if radius is not None:
            params["radius"] = radius
        if speed is not None:
            params["speed"] = speed

        return f"{base_url}?{urlencode(params)}"

    def get_riding_direction_url(self, origin, destination, riding_type=0, road_prefer=0, origin_uid=None, destination_uid=None, coord_type='bd09ll', ret_coordtype='bd09ll', steps_info=0):
        base_url = "https://api.map.baidu.com/directionlite/v1/riding"  # 修改为正确的API接口路径
        params = {
            "origin": origin,
            "destination": destination,
            "riding_type": riding_type,
            "road_prefer": road_prefer,
            "coord_type": coord_type,
            "ret_coordtype": ret_coordtype,
            "steps_info": steps_info,
            "ak": self.api_key  # 确保ak参数显式添加
        }
        if origin_uid:
            params["origin_uid"] = origin_uid
        if destination_uid:
            params["destination_uid"] = destination_uid

        return f"{base_url}?{urlencode(params)}"

    def get_walking_direction_url(self, origin, destination, origin_uid=None, destination_uid=None, coord_type='bd09ll', ret_coordtype='bd09ll', steps_info=0):
        """获取步行路线规划URL
        :param origin: 起点坐标，格式为"纬度,经度"
        :param destination: 终点坐标，格式为"纬度,经度"
        :param origin_uid: 起点POI的uid，可选
        :param destination_uid: 终点POI的uid，可选
        :param coord_type: 输入坐标类型，默认bd09ll
        :param ret_coordtype: 输出坐标类型，默认bd09ll
        :param steps_info: 是否下发step详情，1-下发，0-不下发，默认0
        :return: 百度地图步行路线规划URL
        """
        base_url = "https://api.map.baidu.com/directionlite/v1/walking"
        params = {
            "origin": origin,
            "destination": destination,
            "ak": "47jXQbiwPNWVY5GgVPUJYpOiHG5YhBcr",
            "coord_type": coord_type,
            "ret_coordtype": ret_coordtype,
            "steps_info": steps_info
        }
        if origin_uid:
            params["origin_uid"] = origin_uid
        if destination_uid:
            params["destination_uid"] = destination_uid

        return f"{base_url}?{urlencode(params)}"

    def get_transit_direction_url(self, origin, destination, origin_uid=None, destination_uid=None, coord_type='bd09ll', ret_coordtype='bd09ll', steps_info=0):
        """获取公交路线规划URL
        :param origin: 起点坐标，格式为"纬度,经度"
        :param destination: 终点坐标，格式为"纬度,经度"
        :param origin_uid: 起点POI的uid，可选
        :param destination_uid: 终点POI的uid，可选
        :param coord_type: 输入坐标类型，默认bd09ll
        :param ret_coordtype: 输出坐标类型，默认bd09ll
        :param steps_info: 是否下发step详情，1-下发，0-不下发，默认0
        :return: 百度地图公交路线规划URL
        """
        base_url = "https://api.map.baidu.com/directionlite/v1/transit"
        params = {
            "origin": origin,
            "destination": destination,
            "ak": "47jXQbiwPNWVY5GgVPUJYpOiHG5YhBcr",
            "coord_type": coord_type,
            "ret_coordtype": ret_coordtype,
            "steps_info": steps_info
        }
        if origin_uid:
            params["origin_uid"] = origin_uid
        if destination_uid:
            params["destination_uid"] = destination_uid

        return f"{base_url}?{urlencode(params)}"

    def validate_api_key(self):
        """
        校验API密钥是否有效
        :return: True 如果有效，否则 False
        """
        test_url = "http://api.map.baidu.com/place/v2/search"
        params = {
            "query": "测试地点",
            "region": "北京",
            "output": "json",
            "ak": self.api_key
        }
        try:
            response = requests.get(test_url, params=params)
            response.raise_for_status()
            data = response.json()
            return data.get("status") == 0  # 状态码为0表示成功
        except Exception as e:
            self.logger.error(f"API密钥校验失败: {str(e)}")
            return False
